package com.gs.create.table;

import com.google.common.collect.Lists;
import com.gs.common.tool.consts.DbDriverConst;
import com.gs.common.tool.pojo.OptionItem;
import com.gs.common.tool.utils.SwingUtil;
import com.gs.create.table.utils.SqlUtil;

import javax.swing.*;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.util.Arrays;
import java.util.List;

public class CreatePlaneAndShowUI extends JFrame {

    private static final String fontName = "新宋体";

    private JComboBox<OptionItem> comboBox;
    private JTextPane textPaneInput;
    private JTextPane textPaneOutput;

    public CreatePlaneAndShowUI() {
        setTitle("动态建表工具");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8); // 组件间距
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // ------------------------ 第1行 ------------------------
        JLabel label1 = new JLabel("数据库类型：");
        label1.setFont(new Font(fontName, Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(label1, gbc);
        comboBox = new JComboBox<>(getBizList());
        comboBox.setFont(new Font(fontName, Font.BOLD, 14));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 2; // 占第2、3列
        add(comboBox, gbc);

        // ------------------------ 第2行 ------------------------
        JLabel label2 = new JLabel("输入列定义信息：↓↓↓");
        label2.setFont(new Font(fontName, Font.BOLD, 14));
        label2.setForeground(Color.RED);
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        add(label2, gbc);

        JButton btnHelp = new JButton("使用教程");
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.gridwidth = 1;

        JButton btnProcess = new JButton("开始生成");
        btnProcess.setForeground(Color.blue);
        gbc.gridx = 2;
        gbc.gridy = 1;

        JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
        buttonPanel.add(btnHelp);
        buttonPanel.add(btnProcess);

        add(buttonPanel, gbc);

        // ------------------------ 第3行 ------------------------
        // 左侧：输入 JTextPane
        JScrollPane scrollInput = createScrollableTextPane();
        textPaneInput = (JTextPane) scrollInput.getViewport().getView();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        add(scrollInput, gbc);

        // 中间留空（第1列已占，第2列跳过）
        // 右侧：输出 JTextPane
        JScrollPane scrollOutput = createScrollableTextPane();
        textPaneOutput = (JTextPane) scrollOutput.getViewport().getView();
        textPaneOutput.setEditable(false); // 结果不可编辑
        gbc.gridx = 2;
        gbc.gridy = 2;
        add(scrollOutput, gbc);

        // ------------------------ 按钮事件 ------------------------
        // 按钮1：弹出帮助对话框
        btnHelp.addActionListener(e -> showHelpDialog());

        // 按钮2：处理文本并输出到右侧 JTextPane
        btnProcess.addActionListener(e -> processText());

        //填充下拉框样式
        SwingUtil.showComboBox(comboBox);

        // ------------------------ 窗口设置 ------------------------
        pack();
        setMinimumSize(new Dimension(800, 600));
        setLocationRelativeTo(null); // 居中显示
    }

    // 创建带滚动条的 JTextPane 容器
    private JScrollPane createScrollableTextPane() {
        JTextPane textPane = new JTextPane();
        textPane.setFont(new Font("SansSerif", Font.PLAIN, 14));
        textPane.setText("");
        return new JScrollPane(textPane);
    }

    // 显示帮助信息的对话框
    private void showHelpDialog() {
        JDialog helpDialog = new JDialog(this, "操作帮助", true);
        helpDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        helpDialog.setLayout(new BorderLayout());

        JTextPane helpTextPane = new JTextPane();
        helpTextPane.setContentType("text/html"); // 支持简单 HTML 格式
        helpTextPane.setText(
                "<html><h3>功能说明：</h3>" +
                        "<h4>mysql定义规范</h5>"+
                        "<ul>" +
                        "<li><b>表名定义===></b>表名|表注释</li>" +
                        "<li><b>列定义===><</b>列名|类型|长度|是否主键(1|0),是否自增(1|0),|注释</li>" +
                        "</ul>" +
                        "<h4>postgresql定义规范</h5>"+
                        "<ul>" +
                        "<li><b>表名定义===><</b>表名|表注释</li>" +
                        "<li><b>列定义===><</b>列名|类型|是否主键(1|0)|注释</li>" +
                        "</ul>" +
                        "<p><i>点击【开始生成】生成建表脚本。</i></p>" +
                        "</html>"
        );
        helpTextPane.setEditable(false);
        helpDialog.add(new JScrollPane(helpTextPane), BorderLayout.CENTER);

        JButton closeBtn = new JButton("关闭");
        closeBtn.addActionListener(e -> helpDialog.dispose());

        JPanel btnPanel = new JPanel();
        btnPanel.add(closeBtn);
        helpDialog.add(btnPanel, BorderLayout.SOUTH);

        helpDialog.pack();
        helpDialog.setLocationRelativeTo(this);
        helpDialog.setVisible(true);
    }

    // 处理文本逻辑
    private void processText() {
        //先将输出区域置空
        textPaneOutput.setText("");
        //获取StyledDocument用于格式化文本
        StyledDocument doc = textPaneOutput.getStyledDocument();
        String sqlStr = textPaneInput.getText().trim();
        if (sqlStr.isEmpty()) {
            SwingUtil.writeRowRedText(doc, "表定义信息不能为空!");
            return;
        }
        List<String> columnStrList = Lists.newArrayList(sqlStr.split("\r\n"));
        //第1行是表名|注释，单独处理
        String tableStr = columnStrList.get(0);
        String tableName = tableStr.split("\\|")[0];
        String tableComment = tableStr.split("\\|")[1];
        //删除首行
        columnStrList.remove(tableStr);
        OptionItem optionItem = (OptionItem) comboBox.getSelectedItem();
        String dbType = optionItem.getKey();
        try {
            if (DbDriverConst.MYSQL.equals(dbType)) {
                SwingUtil.writeRowBlueText(doc, SqlUtil.genMysqlCreateTableSql(tableName, tableComment, columnStrList));
            } else if (DbDriverConst.POSTGRESQL.equals(dbType)) {
                SwingUtil.writeRowBlueText(doc, SqlUtil.genHoloCreateTableSql(tableName, tableComment, columnStrList));
            } else {
                SwingUtil.writeRowRedText(doc, "暂不支持此数据库建表");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            SwingUtil.writeRowRedText(doc, ex.getMessage());
        }
    }


    /**
     * 获取业务下拉列表
     */
    private static OptionItem[] getBizList() {
        return Arrays.stream(DbDriverConst.class.getFields()).map(d -> {
            OptionItem optionItem = new OptionItem();
            optionItem.setKey(d.getName().toLowerCase()).setValue(d.getName().toLowerCase());
            return optionItem;
        }).toArray(OptionItem[]::new);
    }
}